<template>
  <view class="theme-switcher" @click="toggleTheme">
    <view class="theme-icon">
      <!-- Show sun icon if dark mode, moon icon if light mode -->
      <sar-icon v-if="isDarkMode" name="sunny-o" size="20px" color="#FFD700" />
      <sar-icon v-else name="moon-o" size="20px" color="#3049BD" />
    </view>
  </view>
</template>

<script lang="ts" setup>
import { onMounted, ref, watch } from 'vue'

// State to track current theme
const isDarkMode = ref(false)

// Function to toggle between light and dark themes
function toggleTheme() {
  isDarkMode.value = !isDarkMode.value
  applyTheme()
}

// Apply the current theme
function applyTheme() {
  // Apply theme attribute to document body
  if (isDarkMode.value) {
    document.documentElement.setAttribute('data-theme', 'dark')
  }
  else {
    document.documentElement.setAttribute('data-theme', 'light')
  }

  // Save theme preference to storage
  try {
    uni.setStorageSync('theme', isDarkMode.value ? 'dark' : 'light')
  }
  catch (e) {
    console.error('Failed to save theme preference:', e)
  }
}

// Load saved theme preference on component mount
onMounted(() => {
  try {
    const savedTheme = uni.getStorageSync('theme')
    if (savedTheme === 'dark') {
      isDarkMode.value = true
    }
    else {
      isDarkMode.value = false
    }
    applyTheme()
  }
  catch (e) {
    console.error('Failed to load theme preference:', e)
  }
})

// Watch for system color scheme changes if no saved preference
watch(() => isDarkMode.value, () => {
  applyTheme()
})
</script>

<style lang="scss" scoped>
.theme-switcher {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 40px;
  height: 40px;
  border-radius: 50%;
  box-shadow: var(--theme-shadow);
  cursor: pointer;
  transition: all 0.3s ease;

  &:active {
    transform: scale(0.95);
  }

  .theme-icon {
    display: flex;
    align-items: center;
    justify-content: center;
  }
}
</style>
